import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { RoomInfo } from '@/api/types'
import { assetService } from '@/api/assetService'

export const useRoomConfigStore = defineStore(
  'roomConfig',
  () => {
    const currentRoom = ref<RoomInfo | null>(null)
    const loading = ref(false)

    // 从本地存储加载配置
    const loadStoredConfig = () => {
      const stored = localStorage.getItem('currentRoomId')
      if (stored) {
        fetchRoomById(parseInt(stored))
      }
    }

    // 设置当前机房
    const setCurrentRoom = (room: RoomInfo | null) => {
      currentRoom.value = room
      if (room) {
        localStorage.setItem('currentRoom', JSON.stringify(room))
        localStorage.setItem('currentRoomId', room.room_id.toString())
      } else {
        localStorage.removeItem('currentRoom')
        localStorage.removeItem('currentRoomId')
      }
    }

    // 获取机房详情
    const fetchRoomById = async (roomId: number) => {
      loading.value = true
      try {
        const response = await assetService.getRoomById(roomId)
        setCurrentRoom(response)
      } catch (err) {
        console.error('获取机房详情失败:', err)
        setCurrentRoom(null)
      } finally {
        loading.value = false
      }
    }

    // 初始化时尝试从localStorage恢复数据
    const initializeStore = () => {
      const storedRoom = localStorage.getItem('currentRoom')
      if (storedRoom) {
        try {
          currentRoom.value = JSON.parse(storedRoom)
        } catch (err) {
          console.error('解析存储的机房信息失败:', err)
          // 如果解析失败，尝试通过ID重新获取
          loadStoredConfig()
        }
      }
    }

    // 立即执行初始化
    initializeStore()

    return {
      currentRoom,
      loading,
      setCurrentRoom,
      loadStoredConfig,
      fetchRoomById,
    }
  },
  {
    // 开启持久化
    persist: true,
  },
)
